package org.apache.http.client.fluent;

import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.entity.ContentType;
import org.apache.http.util.EntityUtils;

class ContentResponseHandler
  implements ResponseHandler<Content>
{
  public Content handleResponse(HttpResponse response)
    throws ClientProtocolException, IOException
  {
    StatusLine statusLine = response.getStatusLine();
    HttpEntity entity = response.getEntity();
    if (statusLine.getStatusCode() >= 300) {
      throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
    }

    if (entity != null) {
      return new Content(EntityUtils.toByteArray(entity), ContentType.getOrDefault(entity));
    }

    return Content.NO_CONTENT;
  }
}